package com.shycloud.mido.member.service.impl;

import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.vo.DistDistributorVO;
import com.shycloud.mido.opter.api.dto.SysUserDto;
import com.shycloud.mido.opter.api.feign.RemoteSysUserService;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.member.mapper.DistDistributorMapper;
import com.shycloud.mido.member.api.entity.DistDistributor;
import com.shycloud.mido.member.service.DistDistributorService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 经销商业务接口实现
 *
 * @author nianhua.jiang
 */
@Service
@AllArgsConstructor
public class DistDistributorServiceImpl extends
		ServiceImpl<DistDistributorMapper, DistDistributor> implements DistDistributorService {

	/** 经销商业务 mapper */
	private final DistDistributorMapper distributorMapper;

	/** 系统用户模块 feign 调用 */
	private final RemoteSysUserService remoteSysUserService;

	/** 密码加密工具类 */
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	/**
	 * 添加经销商
	 *
	 * @param distributorVO
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2021/6/30 10:07
	 */
	@Override
	@Transactional
	public Boolean addDistributor(DistDistributorVO distributorVO) {

		//远程调用查找sysUserId
		Integer sysUserId = (Integer) remoteSysUserService
				.getSysUserIdByName(distributorVO.getPhone()).getData();

		if (sysUserId == 0) {
			//1. 是否有用户 没有则创建
			SysUserDto user = new SysUserDto();
			//用户名
			user.setUsername(distributorVO.getPhone());
			//设置密码
			String pwdStr = ENCODER.encode(StringUtils
					.isEmpty(distributorVO.getPassword()) ? "123456" : distributorVO.getPassword());
			//密码
			user.setPassword(pwdStr);
			distributorMapper.createDistributorUser(user);
			sysUserId = Integer.parseInt(user.getId());
		}

		try {
			//2. 有用户没有权限则加权限
			distributorMapper.createSysUserRole(sysUserId.toString());
		} catch (Exception e) {
			//3. 有用户有权限则报错提示已有经销商
			throw new BusinessException("该手机号已创建过经销商, 请重新输入手机号");
		}

		// 添加经销商
		DistDistributor distributor = new DistDistributor();
		BeanUtils.copyProperties(distributorVO, distributor);
		distributor.setCreateTime(LocalDateTime.now());
		return distributorMapper.insert(distributor) == 1;

	}
}
